import json
import os
import setuptools
import ssl
import subprocess
from urllib.request import urlopen


CLASSIFIERS = """\
Development Status :: 4 - Beta
Intended Audience :: Science/Research
License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
Programming Language :: C
Programming Language :: Python :: 3.8
Programming Language :: Python :: Implementation :: CPython
Topic :: Scientific/Engineering
Operating System :: POSIX :: Linux
Operating System :: MacOS
"""


with open("README.rst") as f:
    long_description = f.read()


def get_version():
    """Get the next version number from PyPI
    """
    version = os.getenv("GRAND_VERSION")
    if not version:
        try:
            _create_unverified_https_context = ssl._create_unverified_context
        except AttributeError:
            pass
        else:
            ssl._create_default_https_context = _create_unverified_https_context

        with urlopen("https://pypi.org/pypi/grand/json") as fd:
            meta = json.load(fd)

        version = meta["info"]["version"]
        numbers = version.split(".")
        numbers[-1] = str(int(numbers[-1]) + 1)
        version = ".".join(numbers)

    p = subprocess.run("git describe --match=NeVeRmAtCh --always --dirty",
                       shell=True, capture_output=True, check=True)
    git_revision = p.stdout.strip().decode()

    with open("grand/version.py", "w+") as f:
        f.write("""\
# This file was generated by setup.py
version = '{version:}'
git_revision = '{git_revision:}'
""".format(version=version, git_revision=git_revision))

    return version


def get_requirements():
    """Load the package requirements
    """
    with open("requirements.txt") as f:
        requirements = []
        for line in f.readlines():
            req = line.strip().split("#", 1)[0]
            if (not req) or req.startswith("#"):
                continue
            requirements.append(req)
        return requirements


setuptools.setup(
    name = "grand",
    version = get_version(),
    maintainer = "GRAND developers",
    maintainer_email = "grand-dev@googlegroups.com",
    description = "Core package for GRAND",
    long_description = long_description,
    long_description_content_type = "text/x-rst",
    url = "https://github.com/grand-mother/grand",
    download_url = "https://pypi.python.org/pypi/grand",
    project_urls = {
        "Bug Tracker"   : "https://github.com/grand-mother/grand/issues",
        "Documentation" : "https://https://grand-mother.github.io/grand-docs",
        "Source Code"   : "https://github.com/grand-mother/grand",
    },
    packages = setuptools.find_packages(exclude=("tests*",)),
    cffi_modules = ('./src/build_core.py:ffi',),
    classifiers = [s for s in CLASSIFIERS.split(os.linesep) if s.strip()],
    license = "LGPLv3",
    platforms = ["Linux", "Mac OS-X"],
    python_requires = ">=3.8",
    install_requires = get_requirements(),
    include_package_data = True,
    package_data = {"": ("libs/data/gull/*", "tools/data/egm96.png")},
    exclude_package_data = {"": ("tools/data/topography/*",)},
)
